import cv2
import os


def process_photos():
    # 证件照规格字典（宽×高 毫米）
    specs = {
        '1cun': (25, 35),  # 标准一寸
        'large_1cun': (33, 48),
        'small_1cun': (22, 32),
        '2cun': (35, 49),
        'large_2cun': (38, 51),
        'small_2cun': (30, 42)
    }

    # 配置参数
    dpi = 300  # 打印分辨率
    input_file = "../../input.jpg"  # 源图片路径
    output_dir = "output"  # 输出目录

    try:
        # 读取原始图片
        img = cv2.imread(input_file)
        if img is None:
            raise FileNotFoundError(f"找不到输入文件：{input_file}")

        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)

        # 获取原始尺寸
        original_h, original_w = img.shape[:2]
        print(f"原始尺寸：{original_w}x{original_h}像素")

        # 批量处理所有规格
        for name, (w_mm, h_mm) in specs.items():
            # 计算目标像素尺寸
            target_w = int(w_mm / 25.4 * dpi)
            target_h = int(h_mm / 25.4 * dpi)

            # 计算宽高比
            target_ratio = target_w / target_h
            original_ratio = original_w / original_h

            # 智能缩放策略
            if original_ratio > target_ratio:
                # 原始更宽：按高度缩放，裁剪左右
                scale = target_h / original_h
                scaled_w = int(original_w * scale)
                scaled_img = cv2.resize(img, (scaled_w, target_h),
                                        interpolation=cv2.INTER_AREA)
                # 计算裁剪位置
                x = (scaled_w - target_w) // 2
                cropped = scaled_img[:, x:x + target_w]
            else:
                # 原始更高：按宽度缩放，裁剪上下
                scale = target_w / original_w
                scaled_h = int(original_h * scale)
                scaled_img = cv2.resize(img, (target_w, scaled_h),
                                        interpolation=cv2.INTER_AREA)
                # 计算裁剪位置
                y = (scaled_h - target_h) // 2
                cropped = scaled_img[y:y + target_h, :]

            # 保存结果
            output_path = os.path.join(output_dir, f"{name}.jpg")
            cv2.imwrite(output_path, cropped)
            print(f"已生成：{name.ljust(10)} {target_w}x{target_h}像素")

        print("所有规格证件照生成完成！输出目录：", os.path.abspath(output_dir))

    except Exception as e:
        print(f"处理失败：{str(e)}")


if __name__ == "__main__":
    process_photos()
